<?php

/**
 * Class name  is ConfigConstantController * @package backend\modules\common\controllers;
 * @author  Womtech  email:chareler@163.com
 * @DateTime 2020-03-06 18:48 
 */

namespace backend\modules\common\controllers;

use Yii;
use common\models\config\ConfigConstant;
use common\models\config\ConfigConstantSearch;
use backend\controllers\BaseController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\utils\ToolUtil;
use common\models\Admin;

/**
 * ConfigConstantController implements the CRUD actions for ConfigConstant model.
 */
class ConfigConstantController extends BaseController
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all ConfigConstant models.
     * @return mixed
     */
    public function actionIndex()
    {
        /*        $searchModel = new ConfigConstantSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
 */
        return $this->render('index', [
            /* 'searchModel' => $searchModel,
            'dataProvider' => $dataProvider, */]);
    }


    public function actionList()
    {
        $searchModel = new ConfigConstantSearch();
        $searchModel->scenario = 'search';
        $rs = $searchModel->search(Yii::$app->request->getBodyParams());


        if ($searchModel->hasErrors()) {
            $return = ToolUtil::returnAjaxMsg(false, '参数有误', ['errors' => $searchModel->errors]);
            return $this->asJson($return);
        }


        /*        //获取需要转化的字段数据(为二维数组),返回需要转化的列,为一维数组,并去重,结果如[1,3,5]
        $arrCreated_id = array_unique(array_column($rs['data'],'created_id'));

        //找到要转换的对应数据,返回二位数组,如[ ['created_id'=>1,'name'=>'admin'] , ['created_id'=>3,'name'=>'test']  ]
        //$arrFields = $this->findModelByFieldValue('tableName',['inputField'=>['value1','value2']],['outField1','outField1']); 
        $arrFields = $this->findModelByFieldValue('\common\models\Admin',['user_id'=>$arrCreated_id],['user_id','username']); 


        //对应整理找到的数据,返回如['10007'=>'admin','10026'=>'test']
        $result = array_column($arrFields,'username','user_id'); 

        $dataOld =  $rs['data']; 
        $data = array();
        //重组数据,加入添加者和修改者姓名内容
        foreach($dataOld as $key=>$value){
            $data[$key]=$value;             
            $username = (array_key_exists($value['created_id'], $result)) ? $result[$value['created_id']] : '';
            $data[$key]["creater"]= $username;
            $data[$key]["updater"]= $username;
        } */





        //$count = $rs['count'];  
        //$data =  $rs['data']; 

        $data = [];
        $basicData = $rs['data'];
        $args = [
            [
                'inputFields' => ['created_id', 'updated_id'],
                'class' => '\common\models\Admin',
                'outFields' => ['user_id', 'username', 'real_name'],
                'keyField' => 'user_id',
                'relation' => [
                    'created_id' => ['toField' => 'username', 'outName' => 'creater'],
                    'updated_id' => ['toField' => 'username', 'outName' => 'updater'],
                ],
                'name' => 'idToUser'
            ]
        ];
        $data = \common\helpers\ModelHelper::attachFieldsValue($basicData, $args);

        return $this->asJson([
            'code' => 0,
            'msg' => '',
            'count' => $rs['count'],
            'data' => $data,
        ]);
    }


 






 



    /**
     * 获取Constant的所有数据
     *
     * @return void
     */
    public function actionGetConstantList()
    {

        $searchModel = new ConfigConstantSearch();
        $searchModel->scenario = 'search';
        $dataProvider = $searchModel->search(Yii::$app->request->getBodyParams());
        if ($searchModel->hasErrors()) {
            $return = ToolUtil::returnAjaxMsg(false, '参数有误', ['errors' => $searchModel->errors]);
            return $this->asJson($return);
        }


        $count = $dataProvider->getTotalCount();
        $dataOld =  $dataProvider->getModels();
        $data = array();
        //重组数据,加入添加者和修改者姓名内容
        foreach ($dataOld as $key => $value) {
            $data[$key] = $value->getAttributes();
            $data[$key]["creater"] = $value->creater->username;
            $data[$key]["updater"] = $value->updater->username;
        }

        return $this->asJson([
            'code' => 0,
            'msg' => '',
            'count' => (int)$count,
            //'data' => $dataProvider->getModels(),
            'data' => $data,
        ]);
    }




    /**
     * Displays a single ConfigConstant model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new ConfigConstant model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $request = Yii::$app->request;

        //如果是表单get提交,如果有参数id,则是更改,没有则是新增
        if ($request->isGet) {
            $id = $this->get('id');
            if (empty($id)) {
                $model = new ConfigConstant();
                return $this->render('create', []);
            } else {
                $model = $this->findModel($id);
                return $this->render('create', [
                    'model' => $model,
                ]);
            }
        }

        if ($request->isPost) {
            //$id = yii::$app->request->post()["ConfigBase"]["id"];
            $id = yii::$app->request->post()["id"];

            //如果没有id,说明是新增
            if (empty($id)) {
                $model = new ConfigConstant();
                if ($model->load($request->post()) && $model->save()) {
                    return ToolUtil::returnAjaxMsg(true, '添加成功');
                } else {
                    return ToolUtil::returnAjaxMsg(false, '添加失败');
                }
            } else {
                $model = $this->findModel($id);
                if ($model->load($request->post()) && $model->save()) {
                    $return = ToolUtil::returnAjaxMsg(true, '修改成功');
                } else {
                    $return = ToolUtil::returnAjaxMsg(false, '修改失败');
                }
                return $this->asJson($return);
            }
        }
    }

    /**
     * Updates an existing ConfigConstant model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing ConfigConstant model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete()
    {
        $request = Yii::$app->request;
        $id = $request->post("id");  //数组格式
        $type = $request->post("type", "hard");
        $result = false;
        //$arrIds = explode(",",$id);
        foreach ($id as $item) {
            $model = $this->findModel($item);
            switch ($type) {
                case 'hard':
                    $result =  $model->delete();
                    break;
                case 'soft':
                    $model->status = -1;
                    $result = $model->save();
                    break;
                default:
                    break;
            }

            if (!($result)) {
                return $this->asJson(ToolUtil::returnAjaxMsg(false, '删除失败'));
            }
        }


        $return = ($result) ? ToolUtil::returnAjaxMsg(true, '删除成功') : ToolUtil::returnAjaxMsg(false, '删除失败');
        return $this->asJson($return);
    }

    /**
     * Finds the ConfigConstant model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return ConfigConstant the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = ConfigConstant::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
    }
}
